package com.start.common.tools;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.start.common.exceptions.StartBusException;

/**
 * xml 工具
 */
public class StartXmlTools {
    private static final XmlMapper objectMapper = new XmlMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 对象转xml
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String objToXml(T object) {


        return objToXml(objectMapper, object);
    }

    /**
     * 对象转xml
     *
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String objToXml(XmlMapper xmlMapper, T object) {
        try {
            return xmlMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new StartBusException(e);
        }

    }

    /**
     * xml 转对象
     *
     * @param clazz
     * @param data
     * @param <T>
     * @return
     */
    public static <T> T xmlToEntity(Class<T> clazz, String data) {
        try {
            return xmlToEntity(objectMapper, clazz, data);
        } catch (Exception e) {
            throw new StartBusException(e);
        }
    }

    /**
     * xml 转对象
     *
     * @param clazz
     * @param data
     * @param <T>
     * @return
     */
    public static <T> T xmlToEntity(XmlMapper xmlMapper, Class<T> clazz, String data) {
        try {
            return xmlMapper.readValue(data, clazz);
        } catch (Exception e) {
            throw new StartBusException(e);
        }
    }

    /**
     * xml 转json
     * @param xml
     * @return
     */
    public static JSONObject xmlToJSON(String xml) {
        return xmlToJSON(objectMapper, xml);
    }
    /**
     * xml 转json
     * @param xml
     * @return
     */
    public static JSONObject xmlToJSON(XmlMapper xmlMapper, String xml) {
        JsonNode jsonNode = null;
        try {
            jsonNode = xmlMapper.readTree(xml);
            String value = jsonNode.textValue();
            return JSONObject.parseObject(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


    }
}
